package com.hfzy.ihk.web.ivr.controller;

import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.facade.ivr.enums.CallInSource;
import com.hfzy.ihk.facade.ivr.vo.CallInto;
import com.hfzy.ihk.web.ivr.biz.CallIntoStartBiz;
import com.hfzy.ihk.web.ivr.constant.Constants;
import com.hfzy.ihk.web.ivr.constant.PublicConfig;
import com.hfzy.ihk.web.ivr.constant.RedisKey;
import com.hfzy.ihk.web.ivr.constant.RedisTimeOut;
import com.hfzy.ihk.web.ivr.context.EventSocketInitBean;
import com.hfzy.ihk.web.ivr.vo.TaobaoTransNumVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2019/5/24.
 */
@RestController
@RequestMapping("/taobaoInvokeDynamicTransNum")
public class TaobaoInvokeDynamicTransNumController {

    private static final Logger logger = LoggerFactory.getLogger(TaobaoInvokeDynamicTransNumController.class);

    @Autowired
    CallIntoStartBiz callIntoStartBiz;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 淘宝转接
     * @param vo
     * @return
     */
    @RequestMapping("/dynamicTrans.do")
    public Map<String,Object> dynamicTransNum(TaobaoTransNumVo vo){
        logger.info("===转接bizid:"+vo.getBiz_id()+",callId:"+vo.getCall_id());


        Map<String,Object> map = new HashMap<>();
        Map<String,Object> dataMap = new HashMap<>();
        CallInto callInto = new CallInto();

        if(StringTools.isEmpty(vo.getCaller_num())
                ||StringTools.isEmpty(vo.getCaller_show_num())
                ||StringTools.isEmpty(vo.getCall_id())){
            map.put("result", Constants.FAIL_STR);
            map.put("msg","缺少必要参数！");
            map.put("data",dataMap);
            return map;
        }

        String sessionId = RedisKey.createSessionId();
        String userShowNum = null;
        ThreadLocalRandom tlr = ThreadLocalRandom.current();
        int per = tlr.nextInt(10);
        if(per<Constants.USE_USER_SHOW_PER_IN) { //百分之30%
            userShowNum = PublicConfig.TAOBAO_USER_SHOW_NUM;
        }else{
            userShowNum = vo.getCaller_show_num();
        }
        try {
            logger.debug("====>taobao call in create sessionId:{}",sessionId);
            callInto.setSessionsId(sessionId);
            callInto.setShowNum(userShowNum);
            callInto.setCallInSource(CallInSource.ALIYUN);
            callInto.setMainCallPhone(vo.getCaller_num());
            callInto.setCallId(vo.getCall_id());
            callInto.setCalledShowNum(vo.getCalled_show_num());
            Map<String,Object> objMap = callIntoStartBiz.callInto(callInto);
            dataMap.put("called_num",objMap.get("targetCallPhone"));

        }catch (Exception e){

            logger.error("呼入获取主显号异常，sessionId:{}",vo.getvSessionId(),e);
            dataMap.put("called_num", "-1");

        }finally {

            map.put("result",Constants.SUCCESS_STR);
            map.put("msg","成功");
            // dataMap.put("called_show_num",vo.getCaller_show_num());
            dataMap.put("called_show_num",userShowNum);
            dataMap.put("call_id",StringTools.isEmpty(vo.getCall_id())?"":vo.getCall_id());
            map.put("data",dataMap);
            //关联sessionId
            try{
                redisTemplate.opsForValue().set(vo.getCall_id(),sessionId, RedisTimeOut.CACHE_ONE_DAY, TimeUnit.SECONDS);
            }catch (Exception e){
                logger.error("taobao call in write redis fali messageId:{},sessionId:{}",vo.getCall_id(),sessionId);
            }

        }
        logger.info("====呼入转接返回参数map：{}",map.toString());
        return map;
    }

    @Autowired
    private EventSocketInitBean eslInitBean;

    /**
     * 测试单呼
     * @param phone
     */
    @RequestMapping("/asrCallOut")
    public void asrCallOut(String phone){
        String sessionid = "7087f7e9-3581-434e-a07f-2dfcb9aeee60";
        redisTemplate.opsForValue().set(RedisKey.ALIBABA_ASR+sessionid, "AWWDm5qtmSkRNOi_Dnr3" + ":" + "AWo4ubRuCTmZu8sLleYf", RedisTimeOut.CACHE_ONE_DAY, TimeUnit.SECONDS);
        final String  callParam = "{origination_uuid=" + sessionid +",origination_caller_id_number=02022953084,origination_caller_id_name=02022953084}sofia/external/99"+phone+"@122.13.6.112:5060 200";
        eslInitBean.addCall(sessionid);  //将本次通话添加到由这个服务发起的通话map中
        eslInitBean.getClient().sendBackgroundApiCommand("originate", callParam);
    }

}
